<?php
require_once 'abstract.php';

/**
 * 
 * Batch Import Products Tags
 * @author aaron
 *
 */
class Mage_Shell_Tags extends Mage_Shell_Abstract
{
	private $_allStoreIds;

	private function _getAllStoreIds()
	{
		if(is_null($this->_allStoreIds)){
			$this->_allStoreIds = array_keys(Mage::getModel('core/store')->getCollection()->toOptionHash());
		}

		return $this->_allStoreIds;
	}
	
	/**
     * Checks inputed tags on the correctness of symbols and split string to array of tags
     *
     * @param string $tagNamesInString
     * @return array
     */
    protected function _extractTags($tagNamesInString)
    {
        return explode(",", $tagNamesInString);
    }
    

	private function _getCsvDir()
	{
		$pathArr = array('var', 'import');
		
		return dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . join(DIRECTORY_SEPARATOR, $pathArr);
	}
	

	protected function _getSourceAdapter($sourceFile)
	{
		return Mage_ImportExport_Model_Import_Adapter::findAdapterFor($sourceFile);
	}
	
	protected function _getProductIds($categoryId)
	{
		$category = Mage::getModel('catalog/category')->load($categoryId);
		$productCollection = Mage::getModel('catalog/product')->getCollection()
			->addCategoryFilter($category);
		
		$productIds = array();
		foreach($productCollection->getData() as $product){
			$productIds[] = $product['entity_id'];
		}
		
		return $productIds;
	}
    
	/**
     * Saving tag and relation between tag, customer, product and store
     */
    public function save($data)
    {
    	extract($data,EXTR_OVERWRITE);
        
    	if ( $categoryId ) {
    		$productIds = $this->_getProductIds($categoryId);
    	} else {
    		$productIds = explode(',', $productIds);
    	}
        if(strlen($tagName) && $productIds) {
        	foreach ($productIds as $productId) {
	            $product = Mage::getModel('catalog/product')
	                ->load($productId);
	            if(!$product->getId()){
	                die('Unable to save tag(s).');
	            } else {
	                try {
	                    $tagModel = Mage::getModel('tag/tag');
	
	                    // added tag relation statuses
	                    $counter = array(
	                        Mage_Tag_Model_Tag::ADD_STATUS_NEW => array(),
	                        Mage_Tag_Model_Tag::ADD_STATUS_EXIST => array(),
	                        Mage_Tag_Model_Tag::ADD_STATUS_SUCCESS => array(),
	                        Mage_Tag_Model_Tag::ADD_STATUS_REJECTED => array()
	                    );
	
	                    $tagNamesArr = $this->_cleanTags($this->_extractTags($tagName));
	                    
	                    foreach ($tagNamesArr as $name) {
	                    	foreach ($stores as $storeId) {
		                        // unset previously added tag data
		                        $tagModel->unsetData()
		                            ->loadByName($name);
		
		                        if (!$tagModel->getId()) {
		                            $tagModel->setName($name)
		                                ->setFirstCustomerId($customerId)
		                                ->setFirstStoreId($storeId)
		                                ->setStatus($tagModel->getApprovedStatus())
		                                ->save();
		                        }
		                        $relationStatus = $tagModel->saveRelation($productId, $customerId, $storeId);
		                        $counter[$relationStatus][] = $name;
	                    	}
	                    }
	                    $this->_fillMessageBox($counter);
	                } catch (Exception $e) {
	                    Mage::logException($e);
	                    die($e->getMessage());
	                }
	            }
        	}
        }
    }

    /**
     * Fill Message Box by success and notice messages about results of user actions.
     *
     * @param array $counter
     * @return void
     */
    protected function _fillMessageBox($counter)
    {
        $session = Mage::getSingleton('catalog/session');

        if (count($counter[Mage_Tag_Model_Tag::ADD_STATUS_NEW])) {
            echo count($counter[Mage_Tag_Model_Tag::ADD_STATUS_NEW])," tag(s) have been accepted for moderation.\n";
        }

        if (count($counter[Mage_Tag_Model_Tag::ADD_STATUS_EXIST])) {
            foreach ($counter[Mage_Tag_Model_Tag::ADD_STATUS_EXIST] as $tagName) {
                echo "Tag \"{$tagName}\" has already been added to the product.\n";
            }
        }

        if (count($counter[Mage_Tag_Model_Tag::ADD_STATUS_SUCCESS])) {
            foreach ($counter[Mage_Tag_Model_Tag::ADD_STATUS_SUCCESS] as $tagName) {
                echo "Tag \"{$tagName}\" has been added to the product.\n";
            }
        }

        if (count($counter[Mage_Tag_Model_Tag::ADD_STATUS_REJECTED])) {
            foreach ($counter[Mage_Tag_Model_Tag::ADD_STATUS_REJECTED] as $tagName) {
                echo "Tag \"{$tagName}\" has been rejected by administrator.\n";
            }
        }
    }
    
    /**
     * Clears the tag from the separating characters.
     *
     * @param array $tagNamesArr
     * @return array
     */
    protected function _cleanTags(array $tagNamesArr)
    {
        $helper = Mage::helper('core');
        foreach( $tagNamesArr as $key => $tagName ) {
            $tagNamesArr[$key] = trim($tagNamesArr[$key], '\'');
            $tagNamesArr[$key] = trim($tagNamesArr[$key]);
            $tagNamesArr[$key] = $helper->escapeHtml($tagNamesArr[$key]);
            if( $tagNamesArr[$key] == '' ) {
                unset($tagNamesArr[$key]);
            }
        }
        return $tagNamesArr;
    }
	
	public function run()
	{
		if($this->getArg('refresh')) {
			Mage::getSingleton('tags/url')
				->refreshTagsRewrites();
			echo "Refresh tag rewrites success!\n";
		} elseif($this->getArg('xml')){
			$xmlFile = $this->_getCsvDir() . DIRECTORY_SEPARATOR . $this->getArg('xml');
        	if (is_file($xmlFile)){
        		$parser = new Varien_Convert_Parser_Xml_Excel();
		    	$io = new Varien_Io_File();
				$xml = $io->read($xmlFile);
				$parser->setVar('single_sheet', 'Sheet 1');
				$parser->setData($xml);
				$parser->parse();
				$xmlData = $parser->getData();
				$feildNames = current($xmlData);
        		while($row = next($xmlData)){
        			$row = array_combine($feildNames, $row);
        			if (
        				( !isset($row['productIds'])
        				&& !isset($row['categoryId']) )
        				|| !isset($row['tagName'])
        				|| !isset($row['customerId'])
        				|| !isset($row['stores'])
        			){
        				die("invalid content format!");
        			}
        			if (empty($row['stores']) || $row['stores'] == 0){
        				$row['stores'] = $this->_getAllStoreIds();
        			} else {
        				$row['stores'] = explode('|', $row['stores']);
        			}
        			$this->save($row);
        		}
        		
				Mage::getSingleton('tags/url')
					->refreshTagsRewrites();
				echo "Refresh tag rewrites success!\n";
        	} else {
        		die("$xmlFile is not exist!");
        	}
		} else {
			echo $this->usageHelp();
		}
	}
	
	/**
     * Retrieve Usage Help Message
     *
     */
    public function usageHelp()
    {
        return <<<USAGE
Usage:  php -f tags.php -- [options]
        php -f tags.php -- import --csv test.csv
        php -f tags.php -- import --xml test.xml
               
  --csv <reviews>           import random reviews from csv file
  --xml <reviews>           import random reviews from xml file
  refresh					refresh tag rewrite
  help                          This help  

USAGE;
    }
}

$shell = new Mage_Shell_Tags();
$shell->run();